<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval-input'" style="display:flex;flex-direction:row;")
              Input.pull-left(style="display:inline-block;width:120px" v-model="formData[item.model1]" :placeholder="item.placeholder1" clearable)
              span.pl-10.pr-10.pull-left.line-h-32 -- 
              Input.pull-left(style="display:inline-block;width:120px" v-model="formData[item.model2]" :placeholder="item.placeholder2" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item,index) of item.radioArr" :key="index" :label="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-120(v-model="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-120(v-model="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
            .pull-right.table-title-btns
              //- Button.mr-10(type="info" size="small" @click="handleShowBatchImportReceivableModal") 批量导入到款
              Button.mr-10(v-if="hasExport" type="info" size="small" @click="handleExport") 导出
          template(slot-scope="{ row, index }" slot="action")
            //- Button.mr-10(type="text" size="small" @click="goReceivePaymentCreate(row.companyID, row.companyCode, row.companyName, row.year, row.month)") 到款填写
            Button.mr-10(v-if="hasAllFeeTotal" type="text" size="small" @click="handleShowTableHuizongbaobiaoModal(row)") 汇总报表查看
            Button.mr-10(v-if="hasSalaryDetails" type="text" size="small" @click="handleShowCustomerSalaryDetailModal(row)") 薪资附件查看
            Button(v-if="hasPostReceivableBalanceLog" type="text" size="small" @click="handleShowBalanceProcessModal(row)") 差额说明
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 汇总报表表格弹窗
    TableHuizongbaobiaoModal(ref="TableHuizongbaobiaoModal")
    //- 薪资附件查看弹窗
    CustomerSalaryDetailModal(ref="CustomerSalaryDetailModal")
    //- 批量导入到款弹窗
    BatchImportReceivableModal(ref="BatchImportReceivableModal" @query="searchFn")
    //- 差额处理弹窗
    BalanceProcessModal(ref="BalanceProcessModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinanceReceivableBillApi } from '@/api/FinanceReceivableBill.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { AccountsReceivableThead } from './ARtableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import TableHuizongbaobiaoModal from '../../../business-sector/customerManage/CustomerBill/modal/tableHuizongbaobiaoModal.vue'
import CustomerSalaryDetailModal from './modal/customerSalaryDetailModal.vue'
import BatchImportReceivableModal from './modal/batchImportReceivableModal.vue'
import BalanceProcessModal from './modal/balanceProcessModal.vue'

export default {
  name: '', // 应收账单管理页面

  components: {
    TableHuizongbaobiaoModal,
    CustomerSalaryDetailModal,
    BatchImportReceivableModal,
    BalanceProcessModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(AccountsReceivableThead),
      tableData: [],
      formData: {
        parentName: '',
        companyName: '',
        companyCode: '',
        FeeYearMonthStart: new Date(),
        FeeYearMonthEnd: new Date(),
        invoiceStatus: '',
        haveBalance: '-1',
        serverName: '',
        productType: '',
        MinAmt: '',
        MaxAmt: ''
      },
      formItem: [
        // { type: 'input', label: '集团公司：', placeholder: '请输入集团公司', prop: 'parentName', model: 'parentName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '所属客服：', placeholder: '请选择所属客服', prop: 'serverName', model: 'serverName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', options: 'server' },
        { type: 'select', label: '产品类别：', placeholder: '请选择产品类别', prop: 'productType', model: 'productType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', options: 'type' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'FeeYearMonthStart', model1: 'FeeYearMonthStart', placeholder2: '结束日期', prop2: 'FeeYearMonthEnd', model2: 'FeeYearMonthEnd', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        // { type: 'radio', label: '开票状态：', placeholder: '请选择开票状态', prop: 'invoiceStatus', model: 'invoiceStatus', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', radioArr: [{ value: '', label: '全部' }, { value: 'true', label: '已开具' }, { value: 'false', label: '未开具' }] },
        { type: 'radio', label: '是否有差额：', placeholder: '请选择是否有差额', prop: 'haveBalance', model: 'haveBalance', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6', radioArr: [{ value: '-1', label: '全部' }, { value: '0', label: '无差额' }, { value: '1', label: '有差额' }] },
        { type: 'interval-input', label: '应到总计：', placeholder1: '应到最小金额', prop1: 'MinAmt', model1: 'MinAmt', placeholder2: '应到最大金额', prop2: 'MaxAmt', model2: 'MaxAmt', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-4' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      downLoadRul: '',
      arrListDown: {
        server: [],
        type: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      currentBillDetail: []
    }
  },

  mounted () {
    var queryData = this.$route.query
    if (queryData) {
      this.formData.companyName = queryData.companyName
      this.formData.FeeYearMonthStart = queryData.date ? queryData.date : new Date()
      this.formData.serverName = queryData.serverName
    }

    this.getEnum()
    this.query()
    this.servers()
  },

  computed: {
    actionArr () {
      console.log(this.$store.state.user)
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 查询
    hasGetList () {
      return this.actionArr.indexOf('GetList') > -1
    },
    // 汇总报表查看
    hasAllFeeTotal () {
      return this.actionArr.indexOf('AllFeeTotal') > -1
    },
    // 薪资附件查看
    hasSalaryDetails () {
      return this.actionArr.indexOf('SalaryDetails') > -1
    },
    // 差额说明
    hasPostReceivableBalanceLog () {
      return this.actionArr.indexOf('PostReceivableBalanceLog') > -1
    }
  },

  methods: {
    // 数据字典
    getEnum () {
      let groupName = 'customer.type'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await FinanceReceivableBillApi.getList({ ...params, ...this.formData })
      console.log('应收res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        console.log('🌈🌈🌈: ', this.tableData)
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
      // this.formData.salaryMonth = val
      // this.getDayList()
    },

    // 导出
    async handleExport () {
      console.log('formData: ', this.formData)
      let res = await FinanceReceivableBillApi.export(this.formData)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('导出应收账单列表 返回链接: ', res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 到款填写
    goReceivePaymentCreate (companyId, companyCode, companyName, periodYear, periodMonth) {
      this.$router.push({
        path: '/ReceivePaymentCreateNew',
        name: 'ReceivePaymentCreateNew',
        query: {
          companyId: companyId,
          companyName: companyName,
          companyCode: companyCode,
          year: periodYear,
          month: periodMonth
        }
      })
    },

    // 显示弹窗-汇总报表表格
    handleShowTableHuizongbaobiaoModal (row) {
      console.log('显示弹窗-汇总报表表格: ', row)
      this.$refs.TableHuizongbaobiaoModal.isShowTableHuizongbaobiaoModal = true
      this.$refs.TableHuizongbaobiaoModal.companyId = row.companyID
      this.$refs.TableHuizongbaobiaoModal.companyName = row.companyName
      this.$refs.TableHuizongbaobiaoModal.year = row.year
      this.$refs.TableHuizongbaobiaoModal.month = row.month
      this.$refs.TableHuizongbaobiaoModal.query()
      this.$refs.TableHuizongbaobiaoModal.customerPayInfo()
    },

    // 显示弹窗-薪资附件
    handleShowCustomerSalaryDetailModal (row) {
      // this.$refs.CustomerSalaryDetailModal.isShowCustomerSalaryDetailModal = true
      console.log('显示弹窗-薪资明细表格: ', row)
      this.$refs.CustomerSalaryDetailModal.isShowCustomerSalaryDetailModal = true
      this.$refs.CustomerSalaryDetailModal.companyId = row.companyID
      this.$refs.CustomerSalaryDetailModal.year = row.year
      this.$refs.CustomerSalaryDetailModal.month = row.month
      this.$refs.CustomerSalaryDetailModal.query()
    },

    // 批量导入到款-上传前文件
    handleBeforeUpload (file) {
      this.file = file
      console.log('file: ', file)
      // return false
    },

    // 批量导入到款成功(当前页面fn)
    handleImportSuccess (res) {
      console.log('批量导入到款res: ', res)
      if (res.code === 200 && res.success) {
        this.$Message.success(res.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    handleShowBatchImportReceivableModal () {
      this.$refs.BatchImportReceivableModal.show()
    },

    // 显示差额处理弹窗
    handleShowBalanceProcessModal (row) {
      console.log('row: ', row)
      // this.$refs.BalanceProcessModal.isShowBalanceProcessModal = true
      this.$refs.BalanceProcessModal.show()
      this.$refs.BalanceProcessModal.currentRow = row
      localStorage.removeItem('tempAddBalanceArr')
      this.$refs.BalanceProcessModal.tableData = []
      this.$refs.BalanceProcessModal.query()
    }

    // // 获取应收账单展开明细
    // async handleOnExpand (row, status) {
    //   if (status) {
    //     console.log('row: ', row)
    //     var data = {
    //       Year: row.year,
    //       Month: row.month,
    //       CompanyID: row.companyID,
    //       Balance: row.allBalanceTotal
    //     }
    //     let res = await FinanceReceivableBillApi.getFinanceReceivableBillListDetail(data)
    //     console.log('获取应收账单展开明细 res: ', res)
    //     if (res.status === 200 && res.data.success) {
    //       row.billDetail = res.data.data
    //     }
    //     console.log('row.billDetail: ',row)
    //   }
    // },

    // async queryBillDetail (row) {
    //   var data = {
    //     Year: row.year,
    //     Month: row.month,
    //     CompanyID: row.companyID,
    //     Balance: row.allBalanceTotal
    //   }
    //   let res = await FinanceReceivableBillApi.getFinanceReceivableBillListDetail(data)
    //   console.log('获取应收账单展开明细 res: ', res)
    //   if (res.status === 200 && res.data.success) {
    //     row.billDetail = res.data.data
    //   }
    // }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
